package gui;

import classes.Evento;
import classes.EventoParticipante;
import classes.Servidor;
import controlador.LoginControlador;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.GeralException;
import fachada.Fachada;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import org.apache.commons.mail.EmailException;
import rn.Email;

public class EventoCadastrar extends javax.swing.JFrame {

    DefaultListModel dlm = new DefaultListModel();
    DefaultListModel dlm2 = new DefaultListModel();

    public EventoCadastrar() {
        initComponents();
        carregarList();
        this.setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textHora = new javax.swing.JTextField();
        try{
            javax.swing.text.MaskFormatter hora= new javax.swing.text.MaskFormatter("##:##");
            textHora = new javax.swing.JFormattedTextField(hora);
        }
        catch (Exception e){
        }
        jLabel3 = new javax.swing.JLabel();
        textEvento = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        textLocal = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        textObs = new javax.swing.JTextArea();
        textData = new com.toedter.calendar.JDateChooser();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        listServidor = new javax.swing.JList();
        jScrollPane5 = new javax.swing.JScrollPane();
        listServidor2 = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        btAddAll = new javax.swing.JButton();
        btAdd = new javax.swing.JButton();
        btRetiraAll = new javax.swing.JButton();
        btRetira = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        btSalvar = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        btLimpar = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Evento");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Data:");

        jLabel2.setText("Hora:");

        jLabel3.setText("Evento:");

        jLabel4.setText("Local:");

        jLabel5.setText("Participantes:");

        jLabel6.setText("Obs.:");

        textObs.setColumns(20);
        textObs.setRows(5);
        textObs.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textObsKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(textObs);

        jLabel7.setText("*");

        jLabel8.setText("*");

        jLabel9.setText("*");

        jLabel10.setText("*");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        listServidor.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane4.setViewportView(listServidor);

        listServidor2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane5.setViewportView(listServidor2);

        btAddAll.setText(">>");
        btAddAll.setToolTipText("Adiciona todos os Servidores da lista.");
        btAddAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddAllActionPerformed(evt);
            }
        });

        btAdd.setText(">");
        btAdd.setToolTipText("Adiciona o Servidor selecionado.");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });

        btRetiraAll.setText("<<");
        btRetiraAll.setToolTipText("Remove todos os Servidores da lista.");
        btRetiraAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRetiraAllActionPerformed(evt);
            }
        });

        btRetira.setText("<");
        btRetira.setToolTipText("Remove o Servidor selecionado.");
        btRetira.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRetiraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(btAdd, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
            .addComponent(btRetira, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
            .addComponent(btRetiraAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(btAddAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addComponent(btRetira)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btAddAll)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btRetiraAll)
                .addGap(52, 52, 52))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE))
                .addContainerGap())
        );

        jLabel12.setText("*");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(1, 1, 1)
                                    .addComponent(jLabel8)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(textHora, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel7))
                                .addComponent(textLocal)
                                .addComponent(textEvento, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel9)
                                .addComponent(jLabel10)))
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5)
                        .addComponent(jLabel12)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(textHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(jLabel7)
                        .addComponent(jLabel8)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textEvento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textLocal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jLabel5))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel12))))
                .addContainerGap())
        );

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        btSalvar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btSalvarKeyPressed(evt);
            }
        });

        jLabel11.setText("* Campos Obrigatórios.");

        btLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/limpar.png"))); // NOI18N
        btLimpar.setText("Limpar");
        btLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparActionPerformed(evt);
            }
        });
        btLimpar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btLimparKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btSalvar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btLimpar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btSalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btLimpar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 317, Short.MAX_VALUE)
                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        try {
            Fachada fachada = new Fachada();
            Servidor s = new Servidor();
            Evento evento = new Evento();
            String lc = LoginControlador.login; //Pega o login.
            s.setLogin(lc);
            fachada.pesquisarLogin(s);//Pesquisa o login.
            EventoParticipante ep = new EventoParticipante();
            evento.setEvento(textEvento.getText().trim());
            evento.setLocal(textLocal.getText().trim());
            evento.setObs(textObs.getText().trim());
            evento.setData(textData.getDate());
            DateFormat sdfHora = new SimpleDateFormat("HH:mm");
            String hora = textHora.getText();
            evento.setHora((java.util.Date) sdfHora.parse(hora));
            sdfHora.setLenient(false);
            evento.setLogado(s);
            evento.setStatus(1);//Status de abertos.
            DateFormat formatdata = new SimpleDateFormat("dd/MM/yyyy");
            Date data = evento.getData();
            String datA = (formatdata.format(data));
            evento = (fachada.consultarid(evento));//pega o ultimo id adicionado.
            int id = evento.getEvento_id() + 1;//Incrementa o id.
            evento.setEvento_id(id);

            ArrayList lista = new ArrayList();
            ArrayList<Servidor> listaServidores = fachada.listar(s);
            DefaultListModel modelol = (DefaultListModel) listServidor2.getModel();
            for (int l = 0; l < modelol.getSize(); l++) {
                String servAtual = modelol.getElementAt(l).toString();
                for (Servidor serv : listaServidores) {
                    if (serv.getNome().equals(servAtual)) {
                        lista.add(serv);
                    }
                }
            }
            ep.setEvento_id(evento);
            ep.setParticipante(lista);
            String nomes = "";
            String separador = "";
            String emails = "";

            for (int n = 0; n < lista.size(); n++) {
                if (lista.size() != 1) {
                    if (n + 1 == lista.size()) {
                        separador = "";
                    } else {
                        separador = ", ";
                    }
                }
                nomes += ep.getParticipante().get(n).getNome() + separador;
                if (ep.getParticipante().get(n).getEmail() == 1) {
                    emails += ep.getParticipante().get(n).getEmailPessoal().toLowerCase().trim() + ",";
                }
                emails += ep.getParticipante().get(n).getEmailProf().toLowerCase().trim() + separador;
            }
            fachada.inserirEvento(evento, ep);

            for (int i = 0; i < lista.size(); i++) {
                Email.assunto = evento.getEvento();
                Email.conteudo = "Data: " + datA + " - Hora:" + hora + "." + "\n" + "Evento: " + evento.getEvento()
                        + "." + "\n" + "Local: " + evento.getLocal() + "." + "\n" + "Observações: " + evento.getObs()
                        + "." + "\n" + "Participantes: " + nomes + ".";
            }
            Email.destino = emails;
            Email e = new Email();
            e.enviaEmail();
            JOptionPane.showMessageDialog(null, "Os e-mails já foram enviados aos participantes!");
            this.dispose();
        } catch (ConexaoException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
        } catch (ConsultaException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível inserir o novo Evento!\n" + e);
        } catch (GeralException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            this.repaint();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "Hora inválida!");
        } catch (EmailException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível enviar o e-mail aos participantes!\n" + ex);
        }

    }//GEN-LAST:event_btSalvarActionPerformed

    private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparActionPerformed
        limpar();
    }//GEN-LAST:event_btLimparActionPerformed

    private void btSalvarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btSalvarKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btSalvarActionPerformed(null);
        }
    }//GEN-LAST:event_btSalvarKeyPressed

    private void btLimparKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btLimparKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btLimparActionPerformed(null);
        }
    }//GEN-LAST:event_btLimparKeyPressed

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        if (listServidor.getSelectedValue() == null) {
            JOptionPane.showMessageDialog(null, "Selecione pelo menos um Servidor.");
        } else {
            for (int i = 0; i < listServidor.getSelectedValuesList().size(); i++) {
                dlm.addElement(listServidor.getSelectedValue());
            }
            listServidor2.setModel(dlm);
            int[] selecao = listServidor.getSelectedIndices();
            for (int i = selecao.length; i > 0; i--) {
                int j = listServidor.getSelectedIndex();
                ((DefaultListModel) listServidor.getModel()).remove(j);
            }
        }
    }//GEN-LAST:event_btAddActionPerformed

    private void btRetiraAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRetiraAllActionPerformed
        int indices = listServidor2.getModel().getSize() + 1;
        final int[] vetor = new int[indices];
        for (int i = 0; i < indices; i++) {
            vetor[i] = i;
        }
        listServidor2.setSelectedIndices(vetor);

        for (int i = 0; i < listServidor2.getSelectedValuesList().size(); i++) {
            dlm2.addElement(listServidor2.getModel().getElementAt(i));
        }
        listServidor.setModel(dlm2);

        int[] selecao = listServidor2.getSelectedIndices();
        for (int i = selecao.length; i > 0; i--) {
            ((DefaultListModel) listServidor2.getModel()).remove(0);
        }
    }//GEN-LAST:event_btRetiraAllActionPerformed

    private void btAddAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddAllActionPerformed
        int indices = listServidor.getModel().getSize() + 1;
        final int[] vetor = new int[indices];
        for (int i = 0; i < indices; i++) {
            vetor[i] = i;
        }
        listServidor.setSelectedIndices(vetor);

        for (int i = 0; i < listServidor.getSelectedValuesList().size(); i++) {
            dlm.addElement(listServidor.getModel().getElementAt(i));
        }
        listServidor2.setModel(dlm);

        int[] selecao = listServidor.getSelectedIndices();
        for (int i = selecao.length; i > 0; i--) {
            ((DefaultListModel) listServidor.getModel()).remove(0);
        }
    }//GEN-LAST:event_btAddAllActionPerformed

    private void btRetiraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRetiraActionPerformed
        if (listServidor2.getSelectedValue() == null) {
            JOptionPane.showMessageDialog(null, "Selecione pelo menos um Servidor.");
        } else {
            dlm2 = (DefaultListModel) listServidor.getModel();
            for (int i = 0; i < listServidor2.getSelectedValuesList().size(); i++) {
                int j = listServidor2.getSelectedIndex();
                dlm2.addElement(listServidor2.getSelectedValue());
            }
            listServidor.setModel(dlm2);

            int[] selecao = listServidor2.getSelectedIndices();
            for (int i = selecao.length; i > 0; i--) {
                int j = listServidor2.getSelectedIndex();
                ((DefaultListModel) listServidor2.getModel()).remove(j);
            }
        }
    }//GEN-LAST:event_btRetiraActionPerformed

    private void textObsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textObsKeyPressed
            textObs.setWrapStyleWord(true);
            textObs.setLineWrap(true);
    }//GEN-LAST:event_textObsKeyPressed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EventoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EventoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EventoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EventoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new EventoCadastrar().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btAddAll;
    private javax.swing.JButton btLimpar;
    private javax.swing.JButton btRetira;
    private javax.swing.JButton btRetiraAll;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable jTable1;
    private javax.swing.JList listServidor;
    private javax.swing.JList listServidor2;
    private com.toedter.calendar.JDateChooser textData;
    private javax.swing.JTextField textEvento;
    private javax.swing.JTextField textHora;
    private javax.swing.JTextField textLocal;
    private javax.swing.JTextArea textObs;
    // End of variables declaration//GEN-END:variables

    public void limpar() {
        textData.setDate(null);
        textEvento.setText("");
        textHora.setText("");
        textLocal.setText("");
        textObs.setText("");
    }

    public final void carregarList() {
        Fachada f = new Fachada();
        Servidor s = new Servidor();
        DefaultListModel modelo = new DefaultListModel();
        ArrayList<Servidor> lista = new ArrayList<Servidor>();
        try {
            lista = f.listar(s);
            for (int i = 0; i < lista.size(); i++) {
                modelo.addElement(lista.get(i).getNome());
            }
            listServidor.setModel(modelo);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a lista de Servidores!\n" + ex);
        }
    }
}
